﻿using cpe.cpein.UI.UserCpeInServiceReference;

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace cpe.cpein.UI.Controls
{
    /// <summary>
    /// Interaction logic for UCUser.xaml
    /// </summary>
    public partial class UCUser : UserControl
    {
        #region Variables declaration

        /// <summary>
        /// Connection to WebService Group
        /// </summary>
        UsersServiceClient userService = new UsersServiceClient();

        /// <summary>
        /// Current User.
        /// </summary>
        User _currentUser;

        /// <summary>
        /// User whom profile is seen
        /// </summary>
        User user;

        /// <summary>
        /// 
        /// </summary>
        List<User> UserRelations;

        /// <summary>
        /// 
        /// </summary>
        List<Skill> UserSkills;

        /// <summary>
        /// Is this the currentuser profile ?
        /// </summary>
        bool MyProfile;

        #endregion

        #region Create and Open

        /// <summary>
        /// Default constructor.
        /// </summary>
        public UCUser()
        {
            InitializeComponent();
        }

        /// <summary>
        /// Constructor with parameters.
        /// </summary>
        /// <param name="p"></param>
        public UCUser(User current, User user)
        {
            this.UserRelations = new List<User>();
            this.UserSkills = new List<Skill>();

            InitializeComponent();
            this._currentUser = current;
            this.user = user;

            MyProfile = (_currentUser.Id == user.Id);

            if (!MyProfile)
            {
                this.btEdit.Visibility   = System.Windows.Visibility.Hidden;
                this.btSave.Visibility   = System.Windows.Visibility.Hidden;
                this.btCancel.Visibility = System.Windows.Visibility.Hidden;
            }
            else
            {
                this.btSave.Visibility   = System.Windows.Visibility.Hidden;
                this.btCancel.Visibility = System.Windows.Visibility.Hidden;
            }

            this.InitializeLists();
        }

        /// <summary>
        /// Function used to to initialize the current UserControl.
        /// </summary>
        private void InitializeUC()
        {
            FillForm();
            this.SetEditable(false);
        }

        /// <summary>
        /// Function fires when control is Loaded.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void UserControl_Loaded(object sender, RoutedEventArgs e)
        {
            InitializeUC();
        }

        /// <summary>
        /// 
        /// </summary>
        private void InitializeLists()
        {
            Tools.Tools.BeginWaitStatus();
            ThreadPool.QueueUserWorkItem(delegate
            {
                List<User> usrs = userService.GetRelations(this.user, this._currentUser);
                List<Skill> skls = userService.GetSkills(this.user, this._currentUser);

                this.Dispatcher.BeginInvoke(new Action(delegate
                {
                    this.UserRelations.Clear();
                    this.UserRelations.AddRange(usrs);
                    this.RelationGrid.ItemsSource = usrs;

                    this.UserSkills.Clear();
                    this.UserSkills.AddRange(skls);
                    this.SkillGrid.ItemsSource = skls;

                    Tools.Tools.EndWaitStatus();
                }));
            });

            if (this.MyProfile)
            {
                this.cmbRelation.Visibility = System.Windows.Visibility.Hidden;
            }
            else
            {
                List<RelationType> relationTypes = userService.GetAllRelationType(false, this._currentUser);
                this.cmbRelation.ItemsSource = relationTypes;

                RelationType relationType = userService.GetRelationType(this.user, this._currentUser);
                if (relationType != null)
                {
                    this.cmbRelation.SelectedValue = relationType.Id;
                }
            }
        }

        #endregion

        #region Events methods


        #endregion

        #region Methods

        /// <summary>
        /// Allow to fill all fields of the User Control with the current object.
        /// </summary>
        private void FillForm()
        {
            if (this.user != null)
            {
                if (MyProfile)
                {
                    this.lblTitleUser.Text = "Mon Profil";
                }
                else
                {
                    this.lblTitleUser.Text = "Profil";
                }
                this.txtUserFirstName.Text = this.user.Name.ToString();
                this.txtUserName.Text = this.user.Lastname.ToString();
                this.txtUserMail.Text = this.user.Email.ToString();
            }
            else
            {
                EmptyForm();
            }
        }


        /// <summary>
        /// Function used to empty fields of the User Control
        /// </summary>
        private void EmptyForm()
        {
            this.txtUserName.Text      = "";
            this.txtUserMail.Text      = "";
            this.txtUserFirstName.Text = "";
        }


        /// <summary>
        /// Allow to set editable or notall fields of the control.
        /// </summary>
        /// <param name="isEditable"></param>
        private void SetEditable(bool isEditable)
        {
            this.txtUserName.IsReadOnly = !isEditable && !MyProfile;
            //this.txtUserName.Background = (!isEditable) ? Brushes.Gray : Brushes.White;

            this.txtUserFirstName.IsReadOnly = !isEditable && !MyProfile;
            //this.txtUserFirstName.Background = (!isEditable) ? Brushes.Gray : Brushes.White;

            this.txtUserMail.IsReadOnly = !isEditable && !MyProfile;
            this.txtUserName.Background = this.txtUserFirstName.Background = this.txtUserMail.Background = (!isEditable) ? Brushes.LightGray : Brushes.White;
        }


        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btEdit_Click(object sender, RoutedEventArgs e)
        {
            this.SetEditable(true);
            this.btEdit.Visibility      = System.Windows.Visibility.Hidden;
            this.btActualize.Visibility = System.Windows.Visibility.Hidden;
            this.btSave.Visibility      = System.Windows.Visibility.Visible;
            this.btCancel.Visibility    = System.Windows.Visibility.Visible;
        }


        /// <summary>
        /// Fired when the "Save" button is clicked
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btSave_Click(object sender, RoutedEventArgs e)
        {
            Object temp  = this.userService.CloneUser(this.user);
            User newUser = temp as User;

            newUser.Name     = this.txtUserFirstName.Text;
            newUser.Lastname = this.txtUserName.Text;
            newUser.Email    = this.txtUserMail.Text;

            this.userService.UpdateUser(newUser, this.user);
            this.SetEditable(false);

            this.btEdit.Visibility      = System.Windows.Visibility.Visible;
            this.btActualize.Visibility = System.Windows.Visibility.Visible;
            this.btSave.Visibility      = System.Windows.Visibility.Hidden;
            this.btCancel.Visibility    = System.Windows.Visibility.Hidden;
        }

        /// <summary>
        /// Fired when the "Actualize" button is clicked
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btActualize_Click(object sender, RoutedEventArgs e)
        {
            ///TODO Retrieve the user from database and refill the profile page
        }

        /// <summary>
        /// Fired when the "Cancel" button is clicked
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btCancel_Click(object sender, RoutedEventArgs e)
        {
            this.FillForm();
            this.SetEditable(false);

            this.btEdit.Visibility      = System.Windows.Visibility.Visible;
            this.btActualize.Visibility = System.Windows.Visibility.Visible;
            this.btSave.Visibility      = System.Windows.Visibility.Hidden;
            this.btCancel.Visibility    = System.Windows.Visibility.Hidden;
        }


        private void btLink_Click(object sender, RoutedEventArgs e)
        {

        }

        /// <summary>
        /// Function which allows to open the group details
        /// </summary>
        /// <param name="p"></param>
        private void OpenUserDetails(int p)
        {
            using (UsersServiceClient us = new UsersServiceClient())
            {
                User user = us.GetUserByID(p, this._currentUser);
                FMainWindow parentWindow = Window.GetWindow(this) as FMainWindow;

                parentWindow.LoadUserControl(new UCUser(this._currentUser, user));
                
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void RelationGrid_DoubleClick(object sender, MouseButtonEventArgs e)
        {
            if (this.RelationGrid.SelectedValue != null)
            {
                OpenUserDetails(int.Parse(this.RelationGrid.SelectedValue.ToString()));
            }
        }


        private void SkillGrid_DoubleClick(object sender, MouseButtonEventArgs e)
        {

        }
        
        #endregion

        private void cmbRelation_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (this.cmbRelation.SelectedValue != null)
            {
                int value = int.Parse(this.cmbRelation.SelectedValue.ToString());
                userService.ChangeRelationType(this.user, this._currentUser, value, this._currentUser);
            }
        }
    }
}